class RemoveKDigits{
  constructor() {

  }
  removeKDigits(num, k) {
    for(let i= 0; i<k; i++) {
      let hasCut = false
      for(let j = 0; j<num.length - 1; j++) {
        if(num.charAt(j) > num.charAt(j + 1)) {
          num = num.slice(0, j) + num.slice(j+1, num.length)
          hasCut = true
          break
        }
      }
      if(!hasCut){
        num = num.slice(0, num.length-1)
      }
    }
    let start = 0
    for(let k = 0; k<num.length-1; k++) {
      if(num.charAt(k) != '0') {
        break
      }
      start++
    }
    num = num.slice(start, num.length)
    if(num.length == 0) {
      return '0'
    }
    return num
  }
  removeKDigitsV2(num, k) {
    let newLength = num.length - k
    let stack = []
    let top = 0
    for(let i=0; i < num.length; i++) {
      let c = num.charAt(i)
      while(top > 0 && stack[top - 1] > c && k > 0) {
        top -= 1
        k -= 1
      } 
      if('0' == c && top == 0) {
        newLength--
        if(newLength <= 0) {
          return '0'
        }
        continue
      }
      stack[top++] = c
    }
    return newLength <= 0 ? '0' : stack.join('')
  }
}

let remove = new RemoveKDigits()
let digit = remove.removeKDigits("51642793", 3)
let v2 = remove.removeKDigitsV2("541270936", 3)
console.log(digit)
console.log(v2)